package com.why.utils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 获取当请求头中的token，其实这里多余，完全可以使用HttpServletRequest来获取
        String authToken = httpServletRequest.getHeader("token");

        // 当token中的username不为空时进行验证token是否是有效的token
        if (StringUtils.hasText(authToken) //&& SecurityContextHolder.getContext().getAuthentication() == null
         ) {
            // 获取到当前用户的account
            String account = JwtUtils.getSubject(authToken); // 验证token是否合法 以及获取用户名

            System.out.println("自定义JWT过滤器获得用户名为"+account);

            // 获取用户的权限信息
            UsernamePasswordAuthenticationToken authentication =
                    (UsernamePasswordAuthenticationToken)redisTemplate.opsForValue().get(account);
            // 将authentication放入SecurityContextHolder中
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        // 放行给下个过滤器
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
